export default class {
  columns = []
  hasSelect = false

  render(h, props, children) {
    children = children || []
    let column = this.getColumnByProps(props)
    props.class = props.class || ''
    props.class += ' h-table-dragable-cell'
    return h('th', { ...props }, [...children, column && this.createDragBar(h, props, column) || undefined])
  }

  createDragBar(h, props, column) {
    if (column.dataIndex === 'h_table_column_action' || !column.width) {
      return null
    }
    let that = this
    return h('div', {
      class: 'h-table-dragable-cell-bar', on: {
        mousedown: (e) => this.onMousedown(e, column),
      }
    })
  }

  onMousedown(e, column) {
    let table = this.getTable(e.target)
    let movingBar = this.createMovingBar()
    let widthDelta = 0
    function mousemove(e) {
      let {y, height} = table.getBoundingClientRect()
      let { clientX: x} = e
      let width = column.width + x - start.startX
      let minWidth = column.minWidth || 100
      let maxWidth = column.maxWidth || 800
      if(width < minWidth) return
      if(width > maxWidth) return
      widthDelta = x - start.startX
      movingBar.style.height = `${height}px`
      movingBar.style.top = `${y}px`
      movingBar.style.left = `${x}px`
    }
    function mouseup(e) {
      let {clientX: endX} = e
      column.width += widthDelta
      // that.columns.splice(0, 0)
      document.body.removeEventListener('mouseup', mouseup)
      document.body.removeEventListener('mousemove', mousemove)
      document.body.style.removeProperty('cursor')
      movingBar.remove()
    }
    let {clientX, clientY} = e
    let start = {startX: clientX, startY: clientY}
    document.body.style.cursor = 'col-resize'
    document.body.addEventListener('mouseup', mouseup)
    document.body.addEventListener('mousemove', mousemove)
    e.preventDefault()
  }

  createMovingBar() {
    let res = document.createElement('div')
    res.className = 'h-table-dragable-cell-moving-bar'
    document.body.append(res)
    return res
  }

  getTable(el) {
    while (el && el.tagName.toLowerCase() !== 'table') el = el.parentNode
    return el
  }

  getColumnByProps(props) {
    if (!props) return null
    let key = props && props.key || undefined
    if (this.hasSelect && typeof key === 'number') {
      key--
    }
    if (!this.columns) this.columns = []
    for (let i = 0; i < this.columns.length; i++) {
      let c = this.columns[i]
      if (c.dataIndex === key || key === i) {
        return c
      }
    }
  }

  setHasSelect(hasSelect) {
    this.hasSelect = hasSelect
  }
  setColumns(columns) {
    this.columns = columns
  }
}